<?php

class Application_Plugin_Acl extends Zend_Controller_Plugin_Abstract{
    
    private $_controller = array(
        'controller' => 'error',
        'action' => 'denied'
    );
    
    public function __construct() 
    {
        $acl = new Zend_Acl();
        
        //roles
        $acl->addRole(new Zend_Acl_Role('guest'));
        $acl->addRole(new Zend_Acl_Role('user'), 'guest');
        $acl->addRole(new Zend_Acl_Role('admin'));
        
        //resources
        $acl->add(new Zend_Acl_Resource('users'));
        $acl->add(new Zend_Acl_Resource('index'));
        $acl->add(new Zend_Acl_Resource('problems'));
        $acl->add(new Zend_Acl_Resource('status'));
        $acl->add(new Zend_Acl_Resource('admin'));
        $acl->add(new Zend_Acl_Resource('algotithms'));
        $acl->add(new Zend_Acl_Resource('olymps'));
        
        
        //permissions
        $acl->deny();
        $acl->allow('admin', null);
        
        //Guest rights
        $acl->allow('guest', null);
        $acl->deny('guest', 'admin');
        $acl->deny('guest', 'users');
        $acl->allow('guest', 'users', array(
            'login', 'registration'
        ));
        
        //User rights
        $acl->allow('user', 'users', array(
            'logout', 'view', 'editname', 'editemail', 'editpassword', 'index', 'image', 'upload', 'calendar'
        ));
                
        Zend_Registry::set('acl', $acl);
    }


    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $auth = Zend_Auth::getInstance();
        $acl = Zend_Registry::get('acl');
       
        if($auth->hasIdentity()) {
            $roles = new Application_Model_Roles();
            $role = $roles->getRole(Zend_Auth::getInstance()->getIdentity()->user_role_id);
        }
        else {
            $role = 'guest';
        }
        
        if (!$acl->hasRole($role)) {
            $role = 'guest';
        }
        
        $controller = $request->controller;
        $action = $request->action;
        
        
        if (!$acl->has($controller)) {
            $controller = null;
        }
        
        if (!$acl->isAllowed($role, $controller, $action)){
            $request->setControllerName($this->_controller['controller']);
            $request->setActionName($this->_controller['action']);
        }
    }
    
}

